import { Game } from "@sapi-game/main";
import { CommonForm, FuncButton } from "sapi-pro";
import { PillarOfFortune } from "./game";
import { PillarOfFortuneMap, PillarOfFortuneMaps } from "./map";
import { PillarOfFortuneLobbyState } from "./states/lobby";

export const POFChooseRoomForm = CommonForm.ButtonForm({
    title: "幸运之柱 - 选择房间",
    body: "请选择一个房间加入",
    buttonGenerator: (player, args) => {
        const buttons: Record<string, FuncButton> = {};

        for (const map of Object.values(PillarOfFortuneMaps)) {
            const game = Game.manager.getGame(PillarOfFortune, map.id);
            const lobbyState = game?.getState(PillarOfFortuneLobbyState);
            const stats = lobbyState?.getStats();

            // 显示房间状态文本
            const text = getRoomStatusText(map, stats, game);

            buttons[text] = {
                func(context) {
                    // 优先获取现有游戏实例
                    let currentGame = Game.manager.getGame(
                        PillarOfFortune,
                        map.id
                    );

                    // 没有则创建新的房间
                    if (!currentGame) {
                        Game.manager.startGame(
                            PillarOfFortune,
                            {
                                map,
                                players: [context.player],
                            },
                            map.id
                        );
                        return;
                    }

                    // 已存在则尝试加入大厅
                    const lobby = currentGame.getState(
                        PillarOfFortuneLobbyState
                    );
                    lobby?.tryJoin(context.player);
                },
            };
        }

        return buttons;
    },
});

function getRoomStatusText(
    map: PillarOfFortuneMap,
    stats?: { cur: number; max: number },
    game?: PillarOfFortune
): string {
    // 无游戏实例
    if (!game) {
        return `${map.name} §8(未开始)`;
    }

    // 有游戏实例但无大厅状态（说明游戏正在进行）
    if (game && !stats) {
        return `§c${map.name} §4(进行中)`;
    }

    // 正常大厅状态
    const { cur, max } = stats!;
    if (cur === 0) {
        return `§a${map.name} §7(${cur}/${max})`;
    } else if (cur < max) {
        return `§e${map.name} §6(${cur}/${max})`;
    } else {
        return `§c${map.name} §4(满员)`;
    }
}
